//----------------------------头文件依赖----------------------------//
#include "dev_uart.h"

//----------------------------函数定义----------------------------//
void uart_debug_init(void)
{
    UART_InitStructure UART_initStruct;

    PORT_Init(PORTM, PIN0, PORTM_PIN0_UART0_RX, 1); // GPIOM.0 配置为 UART0 输入引脚
    PORT_Init(PORTM, PIN1, PORTM_PIN1_UART0_TX, 0); // GPIOM.1 配置为 UART0 输出引脚

    UART_initStruct.Baudrate = 57600;
    UART_initStruct.DataBits = UART_DATA_8BIT;
    UART_initStruct.Parity = UART_PARITY_NONE;
    UART_initStruct.StopBits = UART_STOP_1BIT;
	
    UART_initStruct.RXThreshold = 3;
    UART_initStruct.RXThresholdIEn = 0;
    UART_initStruct.TXThreshold = 3;
    UART_initStruct.TXThresholdIEn = 0;
    UART_initStruct.TimeoutTime = 10;
    UART_initStruct.TimeoutIEn = 0;
	
    UART_Init(UART0, &UART_initStruct);
    UART_Open(UART0);
}

//串口发送-可自定义拓展为 类printf()方法
void uart_send_msg(UART_TypeDef *uart_x, const unsigned char *src_buf, unsigned int num_bytes)
{
    for (unsigned int i = 0; i < num_bytes; i++)
    {
        while (UART_IsTXFIFOFull(uart_x))
            ;
		
        UART_WriteByte(uart_x, *src_buf++);
		while (UART_IsTXBusy(uart_x))
			;//阻塞发送
    }
}

#if !defined(__MICROLIB)// printf(...) 的两种重定向实现: 标准C库		MicroLIB C库

/**
  \brief        不使用 MicroLIB 时避免使用半主机模式
  \param [in]   无
  \return       无
  \note			#pragma import(__use_no_semihosting)
 */
__asm (".global __use_no_semihosting\n\t");
void _sys_exit(int x) 
{
  x = x;
}

//__use_no_semihosting was requested, but _ttywrch was 
void _ttywrch(int ch)
{
    ch = ch;
}

/*
struct __FILE
{
  int handle;
};*/

FILE __stdout;

#endif //!defined(__MICROLIB)

#if defined ( __GNUC__ ) && !defined (__clang__) 
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else 
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif //defined ( __GNUC__ ) && !defined (__clang__) 

PUTCHAR_PROTOTYPE //实现串口发送一个字节数据的函数
{
	UART_WriteByte(UART0, ch);
	
	while (UART_IsTXBusy(UART0))
		;

	return ch;
}
